package com.hui.stock.log;

import com.hui.stock.service.LogService;
import com.hui.stock.utils.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author: ymh
 * @date: 2025/1/13 15:07
 * @description:
 */
@Slf4j
@Component
public class LogInterceptor implements HandlerInterceptor {
    @Autowired
    private LogService logService;

    private final ExecutorService executorService = Executors.newCachedThreadPool();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Log log = handlerMethod.getMethodAnnotation(Log.class);
            if (log != null) {
                // 获取操作描述
                String operation = log.value();
                // 提取用户信息
                String token = request.getHeader("authorization");
                String userName = JwtTokenUtil.getUsername(token);

                // 提取请求信息
                String uri = request.getRequestURI();
                String params = request.getQueryString();
                String ip = getClientIp(request);

                // 异步记录日志
                executorService.submit(() -> logService.recordLog(userName, uri, operation, params, ip));
            }
        }
        return true;
    }

    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (StringUtils.hasText(ip) && !"unknown".equalsIgnoreCase(ip)) {
            return ip.split(",")[0];
        }
        return request.getRemoteAddr();
    }
}
